<template>
    <div class="image-main" v-loading="loading">
        <div class="main-content">
            <el-empty v-if="tableData.length == 0 && !loading" description="暂无图片" />
            <el-row :gutter="10">
                <el-col :md="6" :sm="12" :span="24" :offset="0" v-for="item in tableData" :key="item.id">
                    <el-card shadow="hover" :body-style="{ padding: '0px' }" style="position: relative;margin-bottom: 10px">
                        <el-image
                            style="width: 100%; height: 150px"
                            :src="item.url"
                            fit="cover"
                            :initial-index="0"
                            :preview-src-list="[item.url]"
                        ></el-image>
                        <div class="image-title">
                            {{ item.name }}
                        </div>
                        <div class="image-control" v-permission="['updateImage,POST','deleteImage,POST']">
                            <el-checkbox v-if="openChoose" v-model="item.checked" @change="handleChooseChange(item)" style="margin-right: 8px"></el-checkbox>
                            <el-button link type="primary" size="small" @click="handleEdit(item)" v-permission="['updateImage,POST']">重命名</el-button>
                            <el-popconfirm title="是否要删除该图片？" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(item.id)">
                                <template #reference>
                                    <el-button link type="primary" size="small" v-permission="['deleteImage,POST']">
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <div class="main-footer">
            <el-pagination 
            :currentPage="currentPage" 
            background 
            layout="prev, pager, next"
            :page-size="limit" 
            :total="total" 
            @current-change="getData"></el-pagination>
        </div>
    </div>

    <!-- 新增|修改表单 -->
    <el-drawer v-model="drawer" title="上传图片">
          <el-upload
            class="upload-demo"
            drag
            action="/api/admin/image/upload"
            multiple
            :data="{ image_class_id:searchForm.image_class_id }"
            :headers="{'token': token}"
            @success="handleUploadSuccess"
            @error="handleUploadError"
        >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                Drop file here or <em>click to upload</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500kb
                </div>
            </template>
        </el-upload>
    </el-drawer>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { 
        updateImage,
        getImageList,
        deleteImage
} from '~/api/image'
import { getToken } from '~/composables/auth'
import { toast, showPrompt } from '~/composables/util.js'

const token = getToken()


// 分页参数
const currentPage = ref(1)
const limit = ref(10)
const total = ref(1)

const loading = ref(true)
const showLoading = ()=>loading.value = true
const hideLoading = ()=>loading.value = false

// 表格数据
 const tableData = ref([])

// 查询条件
const searchForm = reactive({
    image_class_id: 168
})

// 获取图片类型id
const loadData = (id)=>{
    currentPage.value = 1
    searchForm.image_class_id = id
    getData()
}

 // 获取表格数据
function getData(page = false) {
    if (typeof page == "number") currentPage.value = page
    tableData.value = []

    // 开启loading
    showLoading()
    getImageList(currentPage.value, searchForm).then((res) => {
        total.value = res.totalCount
        tableData.value = res.list
    }).finally(() => hideLoading())
}

// 上传图片
const drawer = ref(false)
const openUpload = ()=>drawer.value = true
const closeUpload = ()=>drawer.value = false
// 上传成功回调
const handleUploadSuccess = (e)=> {
    getData()
    closeUpload()
}
// 上传失败回调
const handleUploadError = (e)=> {
    toast("上传失败，此功能为演示上传，请替换成自己的服务器地址就行上传！", "error")
    closeUpload()
}

// 重命名
const handleEdit = (item)=>{
    showPrompt("重命名",item.name).then(({ value })=>{
        showLoading()
        updateImage(item.id,{ name:value })
        .then(res => {
            toast("重命名成功")
            getData()
        })
        .finally(() => hideLoading())
    })
}

// 删除
const handleDelete = (id)=>{
        deleteImage([id]).then(res => {
            toast("删除成功")
            getData()
        })
    }

onMounted(() => {
    getData()
})

// 选中图片
const props = defineProps({
    openChoose: {
        type: Boolean,
        default: false
    },
    limit: {
        type: Number,
        default: 1
    }
})
const emit = defineEmits(["choose"])
const checkedImages = computed(() => tableData.value.filter(o => o.checked))
const handleChooseChange = (item) => {
    if (item.checked && checkedImages.value.length > props.limit) {
        item.checked = false
        return toast(`最多只能选中${props.limit}张`, "error")
    }
    emit("choose", checkedImages.value)
}

defineExpose({ openUpload, loadData })
</script>
<style lang="scss" scoped>
.image-main {
    height: 100%;
    position: relative;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 12px;
    background: #fff;
    .main-content {
        flex: 1;
        .image-title {
            position: absolute;
            top: 126px;
            left: 0px;
            right: 0px;
            background: rgba(31, 41, 55, .5);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding: 4px 8px;
            color: #f3f4f6;
            font-size: 14px;
        }
        .image-control {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 8px;
        }
    }
    .main-footer {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 50px;
    }
}
</style>